package com.w.proxy.player.playerproxy.cglib;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * CGLIB动态代理
 *
 * @author wyw
 * @date 2018-10-25
 */
public class LoLCglibDynamicProxy implements MethodInterceptor, Serializable {


    private static final long serialVersionUID = 3054675661051289284L;

    private LoLCglibDynamicProxy() {
    };


    // TODO: 1. 双重校验锁方式的好处与坏处 2. 使用枚举实现单例
    private volatile static LoLCglibDynamicProxy instance;

    /**
     * 双重校验锁获取实例
     *
     * @return 实例对象
     */
    public static LoLCglibDynamicProxy getInstance() {

        if (null == instance) {
            synchronized (LoLCglibDynamicProxy.class) {
                if (null == instance) {
                    instance = new LoLCglibDynamicProxy();
                }
            }
        }
        return instance;
    }

    /**
     * 单例模式(枚举实现)
     */
//    public enum CglibEnum {
//        INSTANCE;
//
//        private LoLCglibDynamicProxy enumInstance;
//        CglibEnum() {
//            enumInstance = new LoLCglibDynamicProxy();
//        }
//
//        public LoLCglibDynamicProxy getInstanceByEnum() {
//            return enumInstance;
//        }
//    }


    public <T> T getProxy(Class<T> cls) {
        return (T) Enhancer.create(cls, this);
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object result = methodProxy.invokeSuper(o, objects);
        return result;
    }

}
